package com.alm.token.ui.activity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.GlideApp;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.bean.ActivityDetailData;
import com.alm.token.ui.data.bean.ActivityIndexData;
import com.alm.token.ui.data.bean.ActivityJoinListData;
import com.alm.token.ui.data.bean.RegisterData;
import com.alm.token.ui.data.bean.UserWalletData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.ActivityView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;
import com.alm.token.utils.LanguageUtils;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import baibeiwallet.Constant;
import baibeiwallet.event.CreateWalletEvent;
import baibeiwallet.event.RefreshActivityEvent;
import baibeiwallet.utils.DialogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;

public class ActivityDeatailActivity extends BaseActivity implements ActivityView<Object> {
    @BindView(R.id.leftItem)
    ImageView leftItem;
    @BindView(R.id.centerItem)
    TextView centerItem;

    @BindView(R.id.tv_buycommit)
    TextView tvBuycommit;
    @BindView(R.id.img_activity_detail_topimg)
    ImageView imgActivityDetailTopimg;
    @BindView(R.id.tv_activity_detail_title)
    TextView tvActivityDetailTitle;
    @BindView(R.id.tv_activity_detail_scannumber)
    TextView tvActivityDetailScannumber;
    @BindView(R.id.img_activity_list_expend)
    ImageView imgActivityListExpend;
    @BindView(R.id.tv_activity_detail_expend)
    TextView tvActivityDetailExpend;
    @BindView(R.id.tv_activity_detail_time)
    TextView tvActivityDetailTime;
    @BindView(R.id.tv_activity_detail_locial)
    TextView tvActivityDetailLocial;
    @BindView(R.id.tv_activity_detail_introducecontent)
    TextView tvActivityDetailIntroducecontent;
    @BindView(R.id.rly_activity_detail)
    RelativeLayout rlyActivityDetail;
    @BindView(R.id.rly_activity_order)
    RelativeLayout rlyActivityOrder;
    @BindView(R.id.img_activity_detail_ordertopimg)
    ImageView imgActivityDetailOrdertopimg;
    @BindView(R.id.tv_activity_detail_ordert_title)
    TextView tvActivityDetailOrdertTitle;
    @BindView(R.id.tv_activity_detail_ordert_locial)
    TextView tvActivityDetailOrdertLocial;
    @BindView(R.id.tv_activity_detail_ordert_time)
    TextView tvActivityDetailOrdertTime;
    @BindView(R.id.tv_activity_detail_order_name)
    TextView tvActivityDetailOrderName;
    @BindView(R.id.tv_activity_detail_order_phone)
    TextView tvActivityDetailOrderPhone;
    @BindView(R.id.tv_activity_detail_order_expend)
    TextView tvActivityDetailOrderExpend;
    @BindView(R.id.tv_buyordercommit)
    TextView tvBuyordercommit;
    @BindView(R.id.ly_top)
    LinearLayout lyTop;

    private ActivityIndexData.DataBean dataBean = new ActivityIndexData.DataBean();
    private ActivityDetailData.DataBean.ActivityDetailBean activityDetail;
    private ActivityDetailData.DataBean.UserOrderBean userOrder;
    private List<ActivityDetailData.DataBean.ProductsBean> products = new ArrayList<>();
    private int staue = -1;

    @Override
    protected MyPreenter initPreenter() {
        return preenter = new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_activitydetail;
    }

    @Override
    protected void initVariables() {
        dataBean = (ActivityIndexData.DataBean) getIntent().getSerializableExtra("databean");
    }

    @Override
    protected void initViews() {
        new ActionBarHelper(this).setTitle(getString(R.string.tv_hint_activity_detail));
    }

    @Override
    protected void loadData() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        preenter.getActivityDetailData(dataBean.getId() + "");
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshActivityEvent(RefreshActivityEvent refreshActivityEvent) {
        preenter.getActivityDetailData(dataBean.getId() + "");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_buycommit:

                if (staue == 2 || staue == 3 || staue == 4) {
//                if (EmptyUtils.isNotEmpty(userOrder)) {
                    Intent intent = new Intent(this, ActivityConfirmationActivity.class);
                    intent.putExtra("databean", (Serializable) userOrder);
//                    startActivityForResult(intent);
                    startActivity(intent);
                } else {
                    if (EmptyUtils.isNotEmpty(products)) {
                        showPopwindow();
                    }
                }

//                if (EmptyUtils.isNotEmpty(userOrder)) {
////                    new ActionBarHelper(this).setTitle("订单确认");
////                    rlyActivityDetail.setVisibility(View.GONE);
////                    rlyActivityOrder.setVisibility(View.VISIBLE);
//                    Intent intent = new Intent(this, ActivityConfirmationActivity.class);
//                    intent.putExtra("databean", dataBean);
////                    startActivityForResult(intent);
//                    startActivity(intent);
//                } else {
//                    Intent intent = new Intent(this, ActivityUserInforActivity.class);
//                    intent.putExtra("databean", dataBean);
//                    startActivity(intent);
//                }

                break;
            case R.id.tv_buyordercommit:
                UserWalletData.DataBean.SysMsgBean sysMsgBean = new UserWalletData.DataBean.SysMsgBean();
                sysMsgBean.setTitle(getString(R.string.common_warmprompt));
                sysMsgBean.setContent(getString(R.string.tv_hint_activity_warm1));
                DialogUtils.showInfor1(this, sysMsgBean, (pwd) -> {

//                    startActivity(ActivityConfirmationActivity.class);
//                        preenter.getEggPartnerAddData(String.valueOf(eggGoodsBeans.get(index).getId()));
                });
//                if (EmptyUtils.isNotEmpty(userOrder)) {
//
//                } else {
//                startActivity(ActivityUserInforActivity.class);
//                }

                break;

            case R.id.ly_top:
                new ActionBarHelper(this).setTitle(getString(R.string.tv_hint_activity_orderdetail));
                rlyActivityDetail.setVisibility(View.VISIBLE);
                rlyActivityOrder.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void getData(Object o) {

    }

    @Override
    public void getActivityIndexData(ActivityIndexData activityIndexData) {

    }

    @Override
    public void getActivityDetailData(ActivityDetailData activityDetailData) {


        if (activityDetailData.getStatus() == 0) {
            if (EmptyUtils.isNotEmpty(activityDetailData.getData())) {
                activityDetail = activityDetailData.getData().getActivityDetail();
                userOrder = activityDetailData.getData().getUserOrder();
                products = activityDetailData.getData().getProducts();
            }
            /**
             * id : 1
             * title : 特使
             * img : http://file.gufang.co/1e9d038c7e500a8f52bc4928956f521.png
             * detailImg : http://file.gufang.co/3a860ddfd773dffde2556039948f164.png
             * price : 15.0
             * moneyType : 1
             * moneyTypeName : ETH
             * moneyTypeImg : http://file.gufang.co/eth_img.png
             * country : 国家
             * city : 城市
             * address : 测试的地址
             * status : 1
             * startTime : 1560147843000
             * endTime : 1561271050000
             * createTime : 1559802255000
             * updateTime : 1560394565000
             * content : 活动内容
             * contentEn : activity content
             * readNum : 0
             */
            if (EmptyUtils.isNotEmpty(activityDetail)) {
                GlideApp.with(this).load(activityDetail.getDetailImg()).into(imgActivityDetailTopimg);
                tvActivityDetailTitle.setText(activityDetail.getTitle());
                tvActivityDetailScannumber.setText(getString(R.string.tv_hint_activity_sacnno, activityDetail.getReadNum() + ""));
                GlideApp.with(this).load(activityDetail.getMoneyTypeImg())
                        .listener(new RequestListener<Drawable>() {
                            @Override
                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
//                                if (EmptyUtils.isNotEmpty(resource)) {
//                                    CommonUtil. changeSVGColor(ActivityDeatailActivity.this, imgActivityListExpend, resource, R.color.black);
//                                    return true;
//                                }
                                return false;
                            }
                        })
                        .error(R.drawable.icon_arctic).into(imgActivityListExpend);
                tvActivityDetailExpend.setText(activityDetail.getPrice() + activityDetail.getMoneyTypeName());
//                tvActivityDetailExpend.setText(activityDetail.getPrice() + " $");
                tvActivityDetailTime.setText(CommonUtil.getDateTimeFromMillisecond2(activityDetail.getStartTime()) + "~" + CommonUtil.getDateTimeFromMillisecond2(activityDetail.getEndTime()));
                tvActivityDetailLocial.setText(activityDetail.getCountry() + activityDetail.getCity() + activityDetail.getAddress());
                if (LanguageUtils.getSetIndex() == 1) {
                    tvActivityDetailIntroducecontent.setText(activityDetail.getContent());
                } else {//en
                    tvActivityDetailIntroducecontent.setText(activityDetail.getContentEn());
                }
            }
            tvBuycommit.setOnClickListener(this);
//            userOrder=new ActivityDetailData.DataBean.UserOrderBean();
//            userOrder.setId(1);
//            userOrder.setOrderId(223);
//            userOrder.setStatus(2);
//            userOrder.setUserPhone("414454");
//            userOrder.setUserRealName("撒大声地");
//            userOrder.setUserRealNameEn("sdsdsds");
            if (EmptyUtils.isNotEmpty(userOrder)) {
//                lyTop.setOnClickListener(this);
//                new ActionBarHelper(this).setTitle("订单确认");
//                rlyActivityDetail.setVisibility(View.GONE);
//                rlyActivityOrder.setVisibility(View.VISIBLE);

//                GlideApp.with(this).load(activityDetail.getDetailImg()).into(imgActivityDetailOrdertopimg);
//                tvActivityDetailOrdertTitle.setText(activityDetail.getTitle());
//                tvActivityDetailOrderExpend.setText("合计:"+activityDetail.getPrice() + activityDetail.getMoneyTypeName());
//                tvActivityDetailOrdertTime.setText(CommonUtil.getDateTimeFromMillisecond2(activityDetail.getStartTime()));
//                tvActivityDetailOrdertLocial.setText(activityDetail.getCountry() + activityDetail.getCity());
//
//                tvActivityDetailOrderName.setText(userOrder.getUserRealName()+" "+userOrder.getUserRealNameEn());
//                tvActivityDetailOrderPhone.setText(userOrder.getUserPhone());
//
//                tvBuyordercommit.setOnClickListener(this);
                staue = userOrder.getStatus();
//                if (staue == 3) {
//                    tvBuycommit.setText("报名详情");
//                    tvBuyordercommit.setText("已报名");
//                    tvBuyordercommit.setOnClickListener(null);
//                } else

                if (staue == 2 || staue == 4) {
                    tvBuycommit.setText(getString(R.string.tv_hint_activity_order_staue_paywait));
//                    tvBuyordercommit.setText("待支付");
                } else if (staue == 3) {
                    tvBuycommit.setText(getString(R.string.tv_hint_activity_registrationdetails));
//                    tvBuyordercommit.setText("待支付");
                } else {
                    tvBuycommit.setText(getString(R.string.tv_hint_activity_signupimmediately));
                }
//                else if (staue == 4) {
//                    tvBuycommit.setText("支付失败，重新支付");
//                }
//                else if (staue == 5) {
//                    tvBuycommit.setText("已退回，重新支付");
//                } else if (staue == 6) {
//                    tvBuycommit.setText("超时，重新支付");
//                } else if (staue == 7) {
//                    tvBuycommit.setText("已取消，重新支付");
//                }

            }
        } else {
            showToast(activityDetailData.getMsg());
        }


//        tvActivityDetailIntroducecontent;

    }

    @Override
    public void getActivityJoinData(RegisterData registerData) {

    }

    @Override
    public void getActivityPayOrderData(RegisterData registerData) {

    }

    @Override
    public void getActivityJoinListData(ActivityJoinListData activityJoinListData) {

    }

    @Override
    public void getCode(RegisterData registerData) {

    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(this,PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            finish();
            showToSetPaypswDialog();
        }else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {

        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {

        showWaitDialog();
    }

    @Override
    public void hideProgress() {

        hideWaitDialog();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    PopupWindow popWindow;

    private void showPopwindow() {
        View parent = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(this, R.layout.view_pop_selecter, null);
        LinearLayout ly_pop_body = popView.findViewById(R.id.ly_pop_body);

        if (EmptyUtils.isNotEmpty(products)) {
            for (int i = 0; i < products.size(); i++) {
                ActivityDetailData.DataBean.ProductsBean productsBean = products.get(i);

                View itemView = View.inflate(this, R.layout.item_pop_activity_products, null);
//                    GlideApp.with(this)
//                            .load(coinBean.getUrl())
//                            .error(R.drawable.icon_invite_ritht)
//                            .into((ImageView) itemView.findViewById(R.id.img_bizhongicon));
                ((TextView) itemView.findViewById(R.id.title)).setText(productsBean.getName());
                ((TextView) itemView.findViewById(R.id.price)).setText(
                        Html.fromHtml(getString(R.string.hangqing_hint_item_value)
                                + ":" + "<font color=#ff0000>" + "$"
                                + CommonUtil.saveToPoint2WithNo(productsBean.getPrice()) + "</font>"));
                ((TextView) itemView.findViewById(R.id.money)).setText(
                        Html.fromHtml(getString(R.string.easteregg_hint_balance)
                                + ":" + "<font color=#444444>" + ""
                                + productsBean.getNum() + "</font>")
                );
                ((TextView) itemView.findViewById(R.id.desc)).setText(Html.fromHtml(getString(R.string.activity_hint_activity_content)
                        + ":" + "<font color=#444444>" + ""
                        + productsBean.getContent() + "</font>"));
                if (productsBean.getNum() == 0) {
                    itemView.setVisibility(View.GONE);
                }

                int finalI = i;
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        bizhongType = finalI;
                        Intent intent = new Intent(ActivityDeatailActivity.this, ActivityUserInforActivity.class);
                        intent.putExtra("databean", dataBean);
                        intent.putExtra("products", (Serializable) products);
                        intent.putExtra("selectId", products.get(finalI).getId());
                        startActivity(intent);

                        popWindow.dismiss();
                    }
                });
                ly_pop_body.addView(itemView);

            }
            ly_pop_body.setBackgroundColor(getResources().getColor(R.color.text_cccccc));
        }

        RelativeLayout outside = popView.findViewById(R.id.pop_outside);

        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;

        if (popWindow == null) {
            popWindow = new PopupWindow(popView, width, height);
            popWindow.setAnimationStyle(R.style.BottomToTopAnim);
//        popWindow.setFocusable(true);
            popWindow.setOutsideTouchable(true);// 设置同意在外点击消失
        }
        outside.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });

        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }


//    @OnClick(R.id.tv_buycommit)
//    public void onViewClicked(View view) {
//        switch (view.getId()) {
//            case R.id.tv_buycommit:
//
//                startActivity(ActivityUserInforActivity.class);
//                break;
//        }
//    }
}
